const multer = require("multer");
const moment = require('moment');
const fs = require('fs');

class uploadService {



    static upload() {

        let basePath = './public/uploadcache/'
        const storage = multer.diskStorage({

            destination: function (req, file, cb) {
                if (!fs.existsSync(basePath)) {
                    fs.mkdirSync(basePath);
                }
                const folderName = moment().format('YYYYMM');
                const path = basePath + folderName;
                if (!fs.existsSync(path)) {
                    fs.mkdirSync(path);
                }
                cb(null, path);
            },
            //给上传文件重命名，获取添加后缀名
            filename: function (req, file, cb) {
                var chars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'P', 'R', 'T', 'W', 'Y', 'M', "N", 'V', 'X', 'Z', 'S'];
                var randomChar = '';
                for (var i = 0; i < 5; i++) {
                    var number = Math.floor(Math.random() * chars.length);
                    randomChar = randomChar + chars[number];
                }

                const fileFormat = (file.originalname).split(".");
                const filename = randomChar + moment().format('X');
                cb(null, filename + "." + fileFormat[fileFormat.length - 1]);
            }
        });

        const upload = multer({
            storage: storage, limits: { fileSize: 20000 * 1024 }, fileFilter: (req, file, cb) => {
                // allow images only
                if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
                    return cb(true);
                }
                cb(null, true);
            },
        });
        return upload;

    }

    static compress(path) {

        const source = tinify.fromFile(path);
        //压缩
        const filename = moment().format('x') + '.png';
        let compressPath = './public/images/' + filename;
        source.toFile(compressPath);
        //缩略图
        const resized = source.resize({
            method: "fit",
            width: 128,
            height: 128
        });
        let thumbPath = './public/thumbs/' + filename;
        resized.toFile(thumbPath);
        return { compressPath, thumbPath };
    }


}


module.exports = uploadService;